<?php
/*******************************************
* Thank-o-matic
* Re-edited by Adk-Team
* www.smfpersonal.net
* 2009-2011
*******************************************/

if (!defined('SMF'))
	die('Hacking attempt...');

// Show all thank you posts by the current user
function showThankYouPosts($memID)
{
	global $txt, $user_info, $scripturl, $modSettings;
	global $context, $user_profile, $sourcedir, $smcFunc;

	// Load the Thank You Post Template :D
	loadTemplate('ThankYouPost');

	// Some initial context.
	$context['start'] = (int) $_REQUEST['start'];
	$context['current_member'] = $memID;

	// Is the load average too high to allow searching just now?
	if (!empty($context['load_average']) && !empty($modSettings['loadavg_show_posts']) && $context['load_average'] >= $modSettings['loadavg_show_posts'])
		fatal_lang_error('loadavg_show_posts_disabled', false);

	// Create the tabs for the template.
	$context[$context['profile_menu_name']]['tab_data'] = array(
		'title' => $txt['thankyoutitle'],
		'description' => $txt['thankyoutitle_help'],
		'tabs' => array(
			'messages' => array(
				'description' => $txt['thankyou_messages_become_desc'],
			),
			'topics' => array(
				'description' => $txt['thankyou_topics_become_desc'],
			),
			'messages_given' => array(
				'description' => $txt['thankyou_messages_given_desc'],
			),
			'topics_given' => array(
				'description' => $txt['thankyou_topics_given_desc'],
			),
		),
	);

	$context['page_title'] = $txt['thankyoutitle'] . ': ' . $user_profile[$memID]['real_name'];

	// Are we just viewing topics?
	$context['is_topics'] = isset($_GET['sa']) && $_GET['sa'] == 'topics' ? true : false;
	// Okay special case woa never thought i will insert them :D but this will be a nice feature :D
	$context['is_messages_given'] = isset($_GET['sa']) && $_GET['sa'] == 'messages_given' ? true : false;
	$context['is_topics_given'] = isset($_GET['sa']) && $_GET['sa'] == 'topics_given' ? true : false;
	$context['is_given'] = $context['is_messages_given'] || $context['is_topics_given'];
	$context['is_messages'] = !($context['is_given'] || $context['is_topics']);

	// If just deleting a message, do it and then redirect back.
	if (isset($_GET['delete']) && !$context['is_topics'])
	{
		checkSession('get');

		// We can be lazy, since removeMessage() will check the permissions for us.
		require_once($sourcedir . '/RemoveTopic.php');
		removeMessage((int) $_GET['delete']);

		// Back to... where we are now ;).
		redirectexit('action=profile;u=' . $memID . ';sa=showThankYouPosts;start=' . $_GET['start']);
	}

	// Default to 10.
	if (empty($_REQUEST['viewscount']) || !is_numeric($_REQUEST['viewscount']))
		$_REQUEST['viewscount'] = '10';

	// This are the Thank You Posts where you give a nice thank you ;D
	if ($context['is_given'])
	{
		$request = $smcFunc['db_query']('', '
			SELECT COUNT(*)
			FROM {db_prefix}thank_you_post AS m' . ($context['is_topics_given'] ? '
				INNER JOIN {db_prefix}topics AS t ON (t.id_first_msg = m.id_msg)' : '') . '
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})
			WHERE m.id_member = {int:current_member}
				' . (!empty($board) ? 'AND m.id_board=' . $board : ''),
			array(
				'current_member' => $memID,
			)
		);
		list ($msgCount) = $smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		$request = $smcFunc['db_query']('', '
			SELECT MIN(id_msg), MAX(id_msg)
			FROM {db_prefix}thank_you_post AS m
			WHERE m.id_member = {int:current_member}
				' . (!empty($board) ? 'AND m.id_board=' . $board : ''),
			array(
				'current_member' => $memID,
			)
		);
		list ($min_msg_member, $max_msg_member) = $smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);
	}
	// That are your current Thankyous that you become from a user :)
	else
	{
		$request = $smcFunc['db_query']('', '
			SELECT COUNT(*)
			FROM {db_prefix}messages AS m' . ($context['is_topics'] ? '
				INNER JOIN {db_prefix}topics AS t ON (t.id_first_msg = m.id_msg)' : '') . '
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})
			WHERE m.id_member = {int:current_member}
				AND m.thank_you_post = 1
				' . (!empty($board) ? 'AND m.id_board=' . $board : '') . '
				' . ($context['user']['is_owner'] ? '' : 'AND m.approved = {int:is_approved}'),
			array(
				'current_member' => $memID,
				'is_approved' => 1,
			)
		);
		list ($msgCount) = $smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		$request = $smcFunc['db_query']('', '
			SELECT MIN(id_msg), MAX(id_msg)
			FROM {db_prefix}messages AS m
			WHERE m.id_member = {int:current_member}
			AND m.thank_you_post = 1
				' . (!empty($board) ? 'AND m.id_board=' . $board : '') . '
				' . ($context['user']['is_owner'] ? '' : 'AND m.approved = {int:is_approved}'),
			array(
				'current_member' => $memID,
				'is_approved' => 1,
			)
		);
		list ($min_msg_member, $max_msg_member) = $smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);
	}

	$reverse = false;
	$range_limit = '';
	$maxIndex = (int) $modSettings['defaultMaxMessages'];

	// Make sure the starting place makes sense and construct our friend the page index.
	$context['page_index'] = constructPageIndex($scripturl . '?action=profile;u=' . $memID . ';area=showThankYouPosts' . ($context['is_topics'] ? ';sa=topics' : ''), $context['start'], $msgCount, $maxIndex);
	$context['current_page'] = $context['start'] / $maxIndex;

	// Reverse the query if we're past 50% of the pages for better performance.
	$start = $context['start'];
	$reverse = $_REQUEST['start'] > $msgCount / 2;
	if ($reverse)
	{
		$maxIndex = $msgCount < $context['start'] + $modSettings['defaultMaxMessages'] + 1 && $msgCount > $context['start'] ? $msgCount - $context['start'] : (int) $modSettings['defaultMaxMessages'];
		$start = $msgCount < $context['start'] + $modSettings['defaultMaxMessages'] + 1 || $msgCount < $context['start'] + $modSettings['defaultMaxMessages'] ? 0 : $msgCount - $context['start'] - $modSettings['defaultMaxMessages'];
	}

	// Guess the range of messages to be shown.
	if ($msgCount > 1000)
	{
		$margin = floor(($max_msg_member - $min_msg_member) * (($start + $modSettings['defaultMaxMessages']) / $msgCount) + .1 * ($max_msg_member - $min_msg_member));
		// Make a bigger margin for topics only.
		if ($context['is_topics'])
			$margin *= 5;

		$range_limit = $reverse ? 'id_msg < ' . ($min_msg_member + $margin) : 'id_msg > ' . ($max_msg_member - $margin);
	}

	$context['page_title'] = $txt['latest_posts'] . ' ' . $txt['thank_you_post_thx_display'] . ' ' . $user_profile[$memID]['real_name'];

	// Find this user's posts.  The left join on categories somehow makes this faster, weird as it looks.
	$looped = false;
	while (true)
	{
		$request = $smcFunc['db_query']('', '
			SELECT
				b.id_board, b.name AS bname, c.id_cat, c.name AS cname, m.id_topic, m.id_msg,
				t.id_member_started, t.id_first_msg, t.id_last_msg, m.body, m.smileys_enabled,
				m.subject, m.poster_time
				, m.thank_you_post_counter, m.thank_you_post
			FROM ' . (!$context['is_given'] ? '{db_prefix}messages AS m' : '{db_prefix}thank_you_post AS tp
				INNER JOIN {db_prefix}messages AS m ON (m.id_msg = tp.id_msg)') . '
				INNER JOIN {db_prefix}topics AS t ON (' . ($context['is_topics'] || $context['is_topics_given'] ? 't.id_first_msg = m.id_msg' : 't.id_topic = m.id_topic') . ')
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
				LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
			WHERE ' . ($context['is_given'] ? 'tp' : 'm') . '.id_member = {int:current_member}
				AND m.thank_you_post = 1
				' . (!empty($board) ? 'AND m.id_board=' . $board : '') . '
				' . (empty($range_limit) ? '' : '
				AND ' . $range_limit) . '
				AND {query_see_board}
				' . ($context['user']['is_owner'] ? '' : 'AND m.approved = {int:is_approved} AND t.approved = {int:is_approved}') . '
			ORDER BY m.id_msg ' . ($reverse ? 'ASC' : 'DESC') . '
			LIMIT ' . $start . ', ' . $maxIndex,
			array(
				'current_member' => $memID,
				'is_approved' => 1,
			)
		);

		// Make sure we quit this loop.
		if ($smcFunc['db_num_rows']($request) === $maxIndex || $looped)
			break;
		$looped = true;
		$range_limit = '';
	}

	// Start counting at the number of the first message displayed.
	$counter = $reverse ? $context['start'] + $maxIndex + 1 : $context['start'];
	$context['posts'] = array();
	$board_ids = array('own' => array(), 'any' => array());
	$thank_you_posts = array();
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		// Censor....
		censorText($row['body']);
		censorText($row['subject']);

		// Do the code.
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);

		// And the array...
		$context['posts'][$counter += $reverse ? -1 : 1] = array(
			'body' => $row['body'],
			'counter' => $counter,
			'category' => array(
				'name' => $row['cname'],
				'id' => $row['id_cat']
			),
			'board' => array(
				'name' => $row['bname'],
				'id' => $row['id_board']
			),
			'topic' => $row['id_topic'],
			'subject' => $row['subject'],
			'start' => 'msg' . $row['id_msg'],
			'time' => timeformat($row['poster_time']),
			'timestamp' => forum_time(true, $row['poster_time']),
			'id' => $row['id_msg'],
			'can_reply' => false,
			'can_mark_notify' => false,
			'can_delete' => false,
			'delete_possible' => ($row['id_first_msg'] != $row['id_msg'] || $row['id_last_msg'] == $row['id_msg']) && (empty($modSettings['edit_disable_time']) || $row['poster_time'] + $modSettings['edit_disable_time'] * 60 >= time()),
			'thank_you_post' => array(
				'locked' => !empty($row['thank_you_post']) && $row['thank_you_post'] > 1,
				'counter' => !empty($row['thank_you_post_counter']) ? $row['thank_you_post_counter'] : '0',
				'isThankYouPost' => !empty($row['thank_you_post']) && $row['thank_you_post'] >= 1,
				'href' => $scripturl . '?action=thankyoupostlist;topic=' . $row['id_topic'] . '.0;msg='.$row['id_msg'],
			),
		);

		$thank_you_posts[] = $row['id_msg'];

		if ($user_info['id'] == $row['id_member_started'])
			$board_ids['own'][$row['id_board']][] = $counter;
		$board_ids['any'][$row['id_board']][] = $counter;
	}
	$smcFunc['db_free_result']($request);

	// All posts were retrieved in reverse order, get them right again.
	if ($reverse)
		$context['posts'] = array_reverse($context['posts'], true);

	// These are all the permissions that are different from board to board..
	if ($context['is_topics'])
		$permissions = array(
			'own' => array(
				'post_reply_own' => 'can_reply',
			),
			'any' => array(
				'post_reply_any' => 'can_reply',
				'mark_any_notify' => 'can_mark_notify',
			)
		);
	else
		$permissions = array(
			'own' => array(
				'post_reply_own' => 'can_reply',
				'delete_own' => 'can_delete',
			),
			'any' => array(
				'post_reply_any' => 'can_reply',
				'mark_any_notify' => 'can_mark_notify',
				'delete_any' => 'can_delete',
			)
		);

	// For every permission in the own/any lists...
	foreach ($permissions as $type => $list)
	{
		foreach ($list as $permission => $allowed)
		{
			// Get the boards they can do this on...
			$boards = boardsAllowedTo($permission);

			// Hmm, they can do it on all boards, can they?
			if (!empty($boards) && $boards[0] == 0)
				$boards = array_keys($board_ids[$type]);

			// Now go through each board they can do the permission on.
			foreach ($boards as $board_id)
			{
				// There aren't any posts displayed from this board.
				if (!isset($board_ids[$type][$board_id]))
					continue;

				// Set the permission to true ;).
				foreach ($board_ids[$type][$board_id] as $counter)
					$context['posts'][$counter][$allowed] = true;
			}
		}
	}

	// Clean up after posts that cannot be deleted.
	foreach ($context['posts'] as $counter => $dummy)
		$context['posts'][$counter]['can_delete'] &= $context['posts'][$counter]['delete_possible'];

	// Load A Preview?
	if (!empty($modSettings['thankYouPostPreview']) && !empty($thank_you_posts))
	{
		// Should i gernerate a list? Need a extra query :)
		require_once ($sourcedir.'/ThankYouPost.php');
		ThankYouPostList($thank_you_posts, true, true);
	}
}

?>